package com.zl.freight.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.zl.freight.R;
import com.zl.freight.ui.activity.LoginActivity;
import com.zl.freight.utils.API;
import com.zl.freight.utils.SoapCallback;
import com.zl.freight.utils.SoapUtils;
import com.zl.freight.utils.SpUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author zhanglei
 *         判断用户是否在其他设备登录的服务
 */
public class IsLoginService extends Service {

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(IsLoginService.this, R.string.is_login_hint, Toast.LENGTH_SHORT).show();
        }
    };

    public IsLoginService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                //检测是否被别人挤掉了
                Map<String, String> map = new HashMap<>();
                map.put("UserId", SpUtils.getUserData(getApplicationContext()).getId());
                map.put("RegistrationId", SpUtils.getRegId(getApplicationContext()));
                SoapUtils.Post(API.CheckUser, map, new SoapCallback() {
                    @Override
                    public void onError(String error) {
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onSuccess(String data) {
                        Boolean aBoolean = Boolean.valueOf(data);
                        if (!aBoolean) {//被人挤掉，提示用户
                            handler.sendEmptyMessage(0);
                        }
                        Log.e("IsLoginService", "onSuccess");
                    }
                });
            }
        };
        timer.schedule(timerTask, 0, 5 * 1000);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
